package com.hz.house.filters;

import com.hz.house.service.StatisticsService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * <p> 使用 zuul filter 进行每日访问量统计，过滤用户id，只统计单次
 * @author lfw
 */
@Component
public class VisitsFilter extends ZuulFilter{

	@Autowired
	private StatisticsService ss;

	@Value("zuul.notNeetTokenUrl.hava")
	private String hava;

	@Override
	public boolean shouldFilter() {
		//只要header包含了授权token的都要处理
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest req = ctx.getRequest();
		if (req.getRequestURI().contains(hava)){
			System.out.println(req.getRequestURI());
			return true;
		}
		String header = req.getHeader("Authorization");
		if(StringUtils.isEmpty(header))
			return false;

		return true;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest req = ctx.getRequest();
		String header = req.getHeader("Authorization");
		if(StringUtils.isEmpty(header)) 
			return null;
		//进行统计逻辑处理
		ss.doStatisticsVisits(header, req.getServletPath());
		return null;
	}

	@Override
	public String filterType() {
		 
		return "pre";
	}

	@Override
	public int filterOrder() {
		 
		return 1;
	}

}
